import pandas as pd
from matplotlib import pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
import warnings
warnings.filterwarnings("ignore")
import statsmodels.api as sm

# 数据导入
df = pd.read_csv("HousePrice_tyHanding.csv")
# DataFrame索引重置
df = df.set_index('DATE')

Min = float('inf')
for i in range(0, 6):  # AIC，BIC最小找到p，q阶数来定阶，从0开始定阶是否可行？？
    for j in range(0, 6):
        result = sm.tsa.ARIMA(df['PRICE'].values.astype(float), order=(i, 1, j)).fit()
        #print([i, j, result.aic, result.bic])
        if result.bic < Min:
            Min = result.bic
            best_pq = [i, j, result.aic, result.bic]
#print(f'最优定阶为{best_pq}')

# 进行模型结果分析和模型检验
Result = sm.tsa.ARIMA(df['PRICE'].values.astype(float), order=(best_pq[0], 1, best_pq[1])).fit()

Predict = Result.predict(start=1, end=len(df['PRICE'])+1)
print(Predict[-1])
Predict = Result.predict(start=1, end=len(df['PRICE'])+2)
print(Predict[-1])
Predict = Result.predict(start=1, end=len(df['PRICE'])+3)
print(Predict[-1])
Predict = Result.predict(start=1, end=len(df['PRICE'])+4)
print(Predict[-1])
Predict = Result.predict(start=1, end=len(df['PRICE'])+5)
print(Predict[-1])
Predict = Result.predict(start=1, end=len(df['PRICE'])+6)
print(Predict[-1])

plt.figure()
plt.plot(range(len(df['PRICE'])), df['PRICE'].values)  # 'o-k'
plt.plot(range(len(df['PRICE']) + 6), Predict)  # 'P--'
plt.legend(('原始观测值', '预测值'))
plt.xticks(list(range(0, len(df['PRICE']), 6)), rotation=90)
plt.show()

